//
//  ISPasswordViewController.m
//  iPhoneSafety
//
//  Created by dlon 2019/1/1.
//  Copyright © 2019年 com.li.ding. All rights reserved.
//

#import "ISPasswordViewController.h"

#import "NWLazyProperty.h"
#import "ISGradientLayerView.h"
#import "UIColor+NWHex.h"
#import <Masonry/Masonry.h>
#import <BlocksKit/BlocksKit.h>
#import <libextobjc/EXTScope.h>
#import <BlocksKit/UIControl+BlocksKit.h>
#import "ISRingServer.h"
#import "ISSafetyAlarmCameraManager.h"
#import "ISWrongView.h"
#import "ISSafetyAlarmMailManager.h"

static const NSString *kISPasswordKey = @"kISPasswordKey";

@implementation ISPassword

static BOOL isPwdShow;

+ (BOOL)isShow {
    return isPwdShow;
}

+ (void)setShow:(BOOL)show {
    isPwdShow = show;
}

+ (NSString *)pwd {
    return [[NSUserDefaults standardUserDefaults] objectForKey:(NSString *)kISPasswordKey];
}

+ (void)savePwd:(NSString *)pwd {
    [[NSUserDefaults standardUserDefaults] setObject:pwd forKey:(NSString *)kISPasswordKey];
}

@end

@interface ISPasswordViewController ()
@property (nonatomic, strong) ISWrongView *wrongView;
@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, strong) NSArray<UIView *> *pwdView;
@property (nonatomic, strong) UIView *pwdViewContent;
@property (nonatomic, strong) NSArray<UIButton *> *inputButtons;
@property (nonatomic, strong) UIView *inputButtonsContent;
@property (nonatomic, strong) UIButton *reInputButton;
@property (nonatomic, strong) UIButton *delButton;
@property (nonatomic, strong) ISGradientLayerView *bgView;

@property (nonatomic, copy) NSString *inputStr;
@property (nonatomic, copy) NSString *cacheStr;

@property (nonatomic, assign) NSInteger verifyWrongCount;
@end

@implementation ISPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.bgView];
    [self.view addSubview:self.pwdViewContent];
    [self.view addSubview:self.inputButtonsContent];
    [self.view addSubview:self.tipLabel];
    [self.pwdView bk_each:^(UIView *obj) {
        [self.pwdViewContent addSubview:obj];
    }];
    [self.inputButtons bk_each:^(UIView *obj) {
        [self.inputButtonsContent addSubview:obj];
    }];
    [self.view addSubview:self.reInputButton];
    [self.view addSubview:self.delButton];
    
    [self.view addSubview:self.wrongView];
    
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.wrongView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(90.f);
        make.centerX.equalTo(self.view);
    }];
    
    NSInteger count = 4;
    CGFloat pwdViewW = 14 * count + 14 * (count - 1);
    CGFloat pwdViewH = 14;
    
    [self.pwdViewContent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tipLabel.mas_bottom).offset(43.f);
        make.size.mas_equalTo(CGSizeMake(pwdViewW, pwdViewH));
        make.centerX.equalTo(self.view);
    }];
    
    [self.pwdView enumerateObjectsUsingBlock:^(UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(14.f, 14.f));
            make.top.equalTo(self.pwdViewContent);
            make.left.equalTo(self.pwdViewContent).offset(idx * 28);
        }];
    }];
    
    [self.inputButtonsContent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pwdViewContent.mas_bottom).offset(50.f);
        make.size.mas_equalTo(CGSizeMake(72 * 3 + 28 * 2, 72 * 4 + 16 * 3));
        make.centerX.equalTo(self.view);
    }];
    
    [self.inputButtons enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(72, 72));
            make.top.equalTo(self.inputButtonsContent).offset(idx / 3 * (72 + 16));
            if (idx == 9) {
                make.centerX.equalTo(self.inputButtonsContent);
            } else {
                make.left.equalTo(self.inputButtonsContent).offset((idx % 3) * (72 + 28));
            }
        }];
    }];
    
    [self.reInputButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(51.f);
        make.bottom.equalTo(self.view).offset(-50.f);
    }];
    
    [self.delButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-51.f);
        make.bottom.equalTo(self.view).offset(-50.f);
    }];
    
    @weakify(self)
    [self bk_addObserverForKeyPath:@"inputStr" task:^(id target) {
        @strongify(self)
        for (int i = 0; i < self.pwdView.count; i ++) {
            self.pwdView[i].backgroundColor = i < self.inputStr.length ? [UIColor nw_colorWithHex:0xffffff] : [UIColor nw_colorWithHex:0xffffff alpha:0.4];
        }
    }];
}

- (void)dealloc {
    [self bk_removeAllBlockObservers];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - private

- (void)inputFinish {
    if (self.type == ISPasswordViewControllerTypeNew) {
        if (self.cacheStr.length > 0) {
            [ISPassword savePwd:self.inputStr];
            [self close];
            if ([self.delegate respondsToSelector:@selector(passwordDidChangedWithType:)]) {
                [self.delegate passwordDidChangedWithType:self.type];
            }
        } else {
            self.cacheStr = self.inputStr;
            self.inputStr = nil;
            self.tipLabel.text = @"请再次输入密码";
        }
    } else if (self.type == ISPasswordViewControllerTypeChg) {
        NSString *pwd = [ISPassword pwd];
        if ([pwd isEqualToString:self.inputStr]) {
            self.type = ISPasswordViewControllerTypeNew;
        } else {
            [self showError];
        }
    } else if (self.type == ISPasswordViewControllerTypeCheck || self.type == ISPasswordViewControllerTypeVerify) {
        NSString *pwd = [ISPassword pwd];
        if ([pwd isEqualToString:self.inputStr]) {
            [self close];
            if ([self.delegate respondsToSelector:@selector(passwordDidChangedWithType:)]) {
                [self.delegate passwordDidChangedWithType:self.type];
            }
        } else {
            [self showError];
            if (self.type == ISPasswordViewControllerTypeVerify) {
                self.verifyWrongCount ++;
                
                if (self.verifyWrongCount > [ISRingServer shareInstance].config.wordTime
                    && [ISRingServer shareInstance].config.wordOn) {
                    [self checkFail];
                }
                NSInteger triggerType = [[[NSUserDefaults standardUserDefaults] valueForKey:@"kISSafetyAlarmMailSendType"] integerValue];
                if (self.verifyWrongCount >= triggerType
                    && [ISSafetyAlarmMailManager sharedInstance].isTakePhotoOn) {
                    [[ISSafetyAlarmCameraManager sharedInstance] takePhotoWithCompletion:^(UIImage * _Nonnull image) {
                        [[ISSafetyAlarmMailManager sharedInstance] sendMailWithmage:image completion:^(BOOL success, NSError * _Nullable error) {
                            
                        }];
                    }];
                }
            }
        }
    }
}

- (void)showError {
    self.inputStr = nil;
    self.tipLabel.text = @"密码错误，请重新输入密码";
}

- (void)checkFail {
    
    self.wrongView.hidden = NO;
    
}

- (void)close {
    [[ISRingServer shareInstance] stopRing];
    [ISPassword setShow:NO];
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:NO completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - set & get

- (void)setType:(ISPasswordViewControllerType)type {
    _type = type;
    switch (type) {
        case ISPasswordViewControllerTypeNew: {
            self.tipLabel.text = @"请输入新密码";
            CAGradientLayer *layer = (CAGradientLayer *)self.bgView.layer;
            layer.colors = @[(id)[UIColor nw_colorWithHex:0x0E6AF3].CGColor,(id)[UIColor nw_colorWithHex:0x05B3F4].CGColor];
        }
            break;
        case ISPasswordViewControllerTypeChg: {
            self.tipLabel.text = @"请输入原来密码";
            CAGradientLayer *layer = (CAGradientLayer *)self.bgView.layer;
            layer.colors = @[(id)[UIColor nw_colorWithHex:0x0E6AF3].CGColor,(id)[UIColor nw_colorWithHex:0x05B3F4].CGColor];
        }
            break;
        case ISPasswordViewControllerTypeCheck:
        case ISPasswordViewControllerTypeVerify:
        {
            self.tipLabel.text = @"请输入密码";
            CAGradientLayer *layer = (CAGradientLayer *)self.bgView.layer;
            layer.colors = @[(id)[UIColor nw_colorWithHex:0xF30E44].CGColor,(id)[UIColor nw_colorWithHex:0xFC2121].CGColor];
        }
            break;
        default:
            break;
    }
    
    self.inputStr = nil;
}

NWLazyPropertyWithInit(UILabel, tipLabel, {
    _tipLabel.font = [UIFont systemFontOfSize:22.f];
    _tipLabel.textColor = [UIColor whiteColor];
})

NWLazyPropertyWithInit(UIButton, reInputButton, {
    [_reInputButton setTitle:@"重新输入" forState:UIControlStateNormal];
    [_reInputButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _reInputButton.titleLabel.font = [UIFont systemFontOfSize:15.f];
    @weakify(self)
    [_reInputButton bk_addEventHandler:^(UIButton *sender) {
        @strongify(self)
        self.inputStr = nil;
    } forControlEvents:UIControlEventTouchUpInside];
})

NWLazyPropertyWithInit(UIView, pwdViewContent, {
    
})

NWLazyPropertyWithInit(UIView, inputButtonsContent, {
    
})

NWLazyPropertyWithInit(UIButton, delButton, {
    [_delButton setTitle:@"删除" forState:UIControlStateNormal];
    [_delButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _delButton.titleLabel.font = [UIFont systemFontOfSize:15.f];
    @weakify(self)
    [_delButton bk_addEventHandler:^(UIButton *sender) {
        @strongify(self)
        if(self.inputStr.length > 0) {
            self.inputStr = [self.inputStr substringToIndex:self.inputStr.length - 1];
        } else {
            self.inputStr = nil;
        }
    } forControlEvents:UIControlEventTouchUpInside];
})

- (NSArray<UIView *> *)pwdView {
    if (!_pwdView) {
        NSMutableArray *list = @[].mutableCopy;
        for (int i = 0; i < 4; i ++) {
            UIView *view = [UIView new];
            view.layer.cornerRadius = 7.f;
            view.clipsToBounds = YES;
            view.backgroundColor = [UIColor nw_colorWithHex:0xffffff alpha:0.4];
            [list addObject:view];
        }
        _pwdView = list;
    }
    return _pwdView;
}

- (NSArray<UIButton *> *)inputButtons {
    if (!_inputButtons) {
        NSMutableArray *list = @[].mutableCopy;
        for (int i = 0; i < 10; i ++) {
            UIButton *button = [UIButton new];
            button.layer.cornerRadius = 36.f;
            button.clipsToBounds = YES;
            button.titleLabel.font = [UIFont systemFontOfSize:24.f];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [button setBackgroundColor:[UIColor nw_colorWithHex:0xffffff alpha:0.2]];
            [button setTitle:[@((i + 1) % 10) stringValue] forState:UIControlStateNormal];
            button.tag = ((i + 1) % 10);
            @weakify(self)
            [button bk_addEventHandler:^(UIButton *sender) {
                @strongify(self)
                if (self.inputStr.length < 4) {
                    self.inputStr = [NSString stringWithFormat:@"%@%ld",(self.inputStr.length > 0 ? self.inputStr : @""),(long)sender.tag];
                }
                if (self.inputStr.length == 4) {
                    [self inputFinish];
                }
            } forControlEvents:UIControlEventTouchUpInside];
            
            [list addObject:button];
        }
        _inputButtons = list;
    }
    return _inputButtons;
}

- (ISGradientLayerView *)bgView {
    if (!_bgView) {
        _bgView = [ISGradientLayerView new];
        CAGradientLayer *layer = (CAGradientLayer *)_bgView.layer;
        layer.startPoint = CGPointMake(0, 1);
        layer.endPoint = CGPointMake(0, 0);
        layer.colors = @[(id)[UIColor nw_colorWithHex:0x0E6AF3].CGColor,(id)[UIColor nw_colorWithHex:0x05B3F4].CGColor];
    }
    return _bgView;
}

NWLazyPropertyWithInit(ISWrongView, wrongView, {
    _wrongView.hidden = YES;
})
@end
